﻿namespace OpalisConsole
{
    using System;
    using System.Runtime.Serialization;
    using System.ServiceModel.DomainServices.Client.ApplicationServices;
    using System.Windows;
    using System.Windows.Controls;
    using OpalisConsole.Controls;
    using OpalisConsole.EndUserService;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Globalization;
    /// <summary>
    /// Main <see cref="Application"/> class.
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// Creates a new <see cref="App"/> instance.
        /// </summary>
        public App()
        {
            InitializeComponent();
            // Create a WebContext and add it to the ApplicationLifetimeObjects
            // collection.  This will then be available as WebContext.Current.
            WebContext webContext = new WebContext();
            //webContext.Authentication = new FormsAuthentication();
            webContext.Authentication = new WindowsAuthentication();
            this.ApplicationLifetimeObjects.Add(webContext);
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // Set App Culture to UI culture
            Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture;
           
            // This will enable you to bind controls in XAML files to WebContext.Current
            // properties
            string UserMachine = e.InitParams["UserMachine"];
            string UserName = e.InitParams["UserAccount"];

            //UserMachine = "172.18.248.92";
            //UserName = "GENMILLS\\G521601";

            string UserID = UserName.Split('\\')[1];
            string UserDomain = UserName.Split('\\')[0];

            this.Resources.Add("WebContext", WebContext.Current);
            this.Resources.Add("MAX_ENTRIES_PER_HOUR", 50);
            this.Resources.Add("ScheduledDate",DateTime.Now.AddHours(1).Subtract(new TimeSpan(0, DateTime.Now.Minute, 0)));
            this.Resources.Add("UserID", UserID);
            this.Resources.Add("FullUserID", UserName);
            this.Resources.Add("ComputerIP", UserMachine);
            this.Resources.Add("UserDomain", UserDomain);
            this.Resources.Add("Computer_ID","Not Approved");
            
            EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
            proxy.getComputerNameCompleted += new EventHandler<getComputerNameCompletedEventArgs>(proxy_getComputerNameCompleted);
            proxy.getComputerNameAsync(UserMachine);
        }

        void proxy_getComputerNameCompleted(object sender, getComputerNameCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.Resources.Add("Status", "Not Owner");
                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.checkGroupMembershipCompleted += new EventHandler<checkGroupMembershipCompletedEventArgs>(proxy_checkGroupMembership_FreshStartAdministrators_Completed);
                proxy.checkGroupMembershipAsync(this.Resources["UserID"].ToString(), "Opalis Self Imaging Administrators", this.Resources["UserDomain"].ToString());
            }
            else
            {
                string computerName = e.Result.ToString();
                this.Resources.Add("ComputerName", computerName);

                string userID = this.Resources["UserID"].ToString();

                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.getComputerOwnerWithUsernameCompleted += new EventHandler<getComputerOwnerWithUsernameCompletedEventArgs>(proxy_getComputerOwnerCompleted);
                proxy.getComputerOwnerWithUsernameAsync(computerName,userID);
            }
        }

        void proxy_getComputerOwnerCompleted(object sender, getComputerOwnerWithUsernameCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.Resources.Add("Status", "Not Owner");
                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.checkGroupMembershipCompleted += new EventHandler<checkGroupMembershipCompletedEventArgs>(proxy_checkGroupMembership_FreshStartAdministrators_Completed);
                proxy.checkGroupMembershipAsync(this.Resources["UserID"].ToString(), "Opalis Self Imaging Administrators", this.Resources["UserDomain"].ToString());
            }
            else
            {
                string ownerName = e.Result.ToString();
                string requester = this.Resources["FullUserID"].ToString().ToUpper();
                //owner
                if (requester.Contains(ownerName.ToUpper()) && !ownerName.Equals(String.Empty))
                {
                    EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                    proxy.getApprovedComputerIDCompleted += new EventHandler<getApprovedComputerIDCompletedEventArgs>(proxy_getApprovedComputerIDCompleted);
                    proxy.getApprovedComputerIDAsync(this.Resources["ComputerName"].ToString());
                }
                //not Owner
                else
                {
                    this.Resources.Add("Status", "Not Owner");
                    EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                    proxy.checkGroupMembershipCompleted += new EventHandler<checkGroupMembershipCompletedEventArgs>(proxy_checkGroupMembership_FreshStartAdministrators_Completed);
                    proxy.checkGroupMembershipAsync(this.Resources["UserID"].ToString(), "Opalis Self Imaging Administrators", this.Resources["UserDomain"].ToString());
                }
            }
        }
        void proxy_getApprovedComputerIDCompleted(object sender, getApprovedComputerIDCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.InitializeRootVisual();
                throw new Exception();
            }
            else
            {
                String computerID = e.Result.ToString();
                if (this.Resources.Contains("Computer_ID"))
                {
                    this.Resources.Remove("Computer_ID");
                }
                
                this.Resources.Add("Computer_ID", computerID);

                if (computerID.Equals("Not Approved"))
                {
                    this.Resources.Add("Status", "Not Approved");
                    EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                    proxy.checkGroupMembershipCompleted += new EventHandler<checkGroupMembershipCompletedEventArgs>(proxy_checkGroupMembership_FreshStartAdministrators_Completed);
                    proxy.checkGroupMembershipAsync(this.Resources["UserID"].ToString(), "Opalis Self Imaging Administrators", this.Resources["UserDomain"].ToString());
                }
                else
                {
                    EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                    proxy.getRequestStatusCompleted += new EventHandler<getRequestStatusCompletedEventArgs>(proxy_getRequestStatusCompleted);
                    proxy.getRequestStatusAsync(this.Resources["ComputerName"].ToString());
                }
            }
        }
        void proxy_getRequestStatusCompleted(object sender, getRequestStatusCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.InitializeRootVisual();
                throw new Exception();
            }
            else
            {
                String result = e.Result.ToString();
                if (result.Equals("Not Scheduled"))
                {
                    this.Resources.Add("Status", "Not Scheduled");
                }
                else
                {
                    String Imaging_ID = result.Split(',')[0];
                    String OSDComputerName = result.Split(',')[1];
                    String Status = result.Split(',')[2];
                    DateTime StartDateTime = Convert.ToDateTime(result.Split(',')[3]).ToLocalTime();
                    String userDataYN = result.Split(',')[4];

                    if (Status.Equals("Scheduling") || Status.Equals("New")) { this.Resources.Add("Status", "Scheduled"); }
                    else { this.Resources.Add("Status", Status); }
                    this.Resources.Remove("ScheduledDate");
                    this.Resources.Add("ScheduledDate", StartDateTime);
                    this.Resources.Add("Imaging_ID", Imaging_ID);
                    this.Resources.Add("Data Choice", userDataYN);
                }

                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.getEntriesPerDayCompleted += new EventHandler<getEntriesPerDayCompletedEventArgs>(proxy_getEntriesPerDayCompleted);

                TimeSpan span = DateTime.UtcNow.Subtract(DateTime.Now);
                String minutes = Math.Round(span.TotalMinutes).ToString();
                proxy.getEntriesPerDayAsync(minutes);
            }
        }
        void proxy_getEntriesPerDayCompleted(object sender, getEntriesPerDayCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.InitializeRootVisual();
                throw new Exception();
            }
            else
            {
                if (e.Result.Count > 0)
                {
                    List<EntriesPerDate> dayList = new List<EntriesPerDate>();
                    foreach (EntriesPerDate entry in e.Result)
                    {
                        if (entry.NumberOfScheduled > (int)this.Resources["MAX_ENTRIES_PER_HOUR"] * 24)
                        {
                            dayList.Add(entry);
                        }
                    }
                    if (dayList.Count != 0) { this.Resources.Add("DAY_LIST", dayList); }
                    else
                    {
                        dayList.Add(new EntriesPerDate() { Day = DateTime.Now.AddDays(-1), NumberOfScheduled = 0 });
                        this.Resources.Add("DAY_LIST", dayList);
                    }

                }

                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.checkGroupMembershipCompleted += new EventHandler<checkGroupMembershipCompletedEventArgs>(proxy_checkGroupMembership_FreshStartAdministrators_Completed);
                proxy.checkGroupMembershipAsync(this.Resources["UserID"].ToString(), "Opalis Self Imaging Administrators", this.Resources["UserDomain"].ToString());

            }
        }
        void proxy_checkGroupMembership_FreshStartAdministrators_Completed(object sender, checkGroupMembershipCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.InitializeRootVisual();
                throw new Exception();
            }
            else
            {
                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.checkGroupMembershipCompleted += new EventHandler<checkGroupMembershipCompletedEventArgs>(proxy_checkGroupMembershipCompleted_Developer);
                proxy.checkGroupMembershipAsync(App.Current.Resources["UserID"].ToString(), "GMI_APP_MSDN_Microsoft_SI", App.Current.Resources["UserDomain"].ToString());
                if ((bool)e.Result) { this.Resources.Add("FreshStartAdmin", true); }
                else { this.Resources.Add("FreshStartAdmin", false); }         
            }
        }
        void proxy_checkGroupMembershipCompleted_Developer(object sender, checkGroupMembershipCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.InitializeRootVisual();
                throw new Exception();
            }
            else
            {
                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.checkGroupMembershipCompleted +=new EventHandler<checkGroupMembershipCompletedEventArgs>(proxy_checkGroupMembershipCompleted_FreshStartApprover);
                proxy.checkGroupMembershipAsync(App.Current.Resources["UserID"].ToString(), "Opalis Self Imaging Approvers", App.Current.Resources["UserDomain"].ToString());
                if ((bool)e.Result) { this.Resources.Add("DeveloperStatus", true); }
                else { this.Resources.Add("DeveloperStatus", false); }
            }
        }
        void proxy_checkGroupMembershipCompleted_FreshStartApprover(object sender, checkGroupMembershipCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                this.InitializeRootVisual();
                throw new Exception();
            }
            else
            {
                if ((bool)e.Result) { this.Resources.Add("FreshStartApprover", true); }
                else { this.Resources.Add("FreshStartApprover", false); }

                this.InitializeRootVisual();
            }
        }

        
        
        

        /// <summary>
        /// Invoked when the <see cref="LoadUserOperation"/> completes. Use this
        /// event handler to switch from the "loading UI" you created in
        /// <see cref="InitializeRootVisual"/> to the "application UI"
        /// </summary>
        private void Application_UserLoaded(LoadUserOperation operation)
        {
        }

        /// <summary>
        /// Initializes the <see cref="Application.RootVisual"/> property. The
        /// initial UI will be displayed before the LoadUser operation has completed
        /// (The LoadUser operation will cause user to be logged automatically if
        /// using windows authentication or if the user had selected the "keep
        /// me signed in" option on a previous login).
        /// </summary>
        protected virtual void InitializeRootVisual()
        {
            /*
            this.busyIndicator = new BusyIndicator();
            this.busyIndicator.Content = new MainPage();
            this.busyIndicator.HorizontalContentAlignment = HorizontalAlignment.Stretch;
            this.busyIndicator.VerticalContentAlignment = VerticalAlignment.Stretch;

            this.RootVisual = this.busyIndicator;
            */

            ScrollViewer root = new ScrollViewer();
            root.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
            root.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            root.Content = new MainPage();
            this.RootVisual = root;
        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // a ChildWindow control.
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                ErrorWindow.CreateNew(e.ExceptionObject);
            }
        }
    }
}